import Vue from 'vue'
import VueRouter from 'vue-router'

// () => import(/* webpackChunkName: "about" */ '../views/About.vue')
const Login = () => import('@/views/login/index.vue')
const Home = () => import('@/views/home/index.vue')
const Article = () => import('@/views/article/index.vue')
const Publish = () => import('@/views/publish/index.vue')
const Image = () => import('@/views/image/index.vue')
const Comment = () => import('@/views/comment/index.vue')
const Settings = () => import('@/views/settings/index.vue')
const Fans = () => import('@/views/fans/index.vue')

const LayOut = () => import('@/views/layout/index.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    // name: 'layout', // 命名路由layout有一个默认子路由  这个名字没有意义 正确做法：如果有默认子路由，就不要给父路由起名字
    component: LayOut,
    children: [
      {
        path: '', // path为空 会作为默认子路由渲染
        name: 'home',
        component: Home
      },
      {
        path: '/article', // path为空 会作为默认子路由渲染
        name: 'article',
        component: Article
      },
      {
        path: '/publish', // path为空 会作为默认子路由渲染
        name: 'publish',
        component: Publish
      },
      {
        path: '/image', // path为空 会作为默认子路由渲染
        name: 'image',
        component: Image
      },
      {
        path: '/comment', // path为空 会作为默认子路由渲染
        name: 'comment',
        component: Comment
      },
      {
        path: '/settings', // path为空 会作为默认子路由渲染
        name: 'settings',
        component: Settings
      },
      {
        path: '/fans', // path为空 会作为默认子路由渲染
        name: 'fans',
        component: Fans
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const user = JSON.parse(window.localStorage.getItem('user'))
  // 校验非登录页面的登录状态
  if (to.path !== '/login') {
    if (user) {
      // 已登录允许通过
      next()
    } else {
      // 没有登录 跳转到登录页面
      next('/login')
    }
  } else {
    next()
  }
})

export default router
